package cn.iocoder.yudao.framework.jackson.core;

import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 *  TODO 新增
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 会将秒级时间戳、毫秒级时间戳、ISO格式的日期时间及中国格式的日期时间反序列化为 {@link LocalDateTime}
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2024/05/02
 * @see com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer
 * @see cn.iocoder.yudao.framework.common.util.json.databind.TimestampLocalDateTimeDeserializer
 */
@Slf4j
@JacksonStdImpl
public class EnhancedLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    public static final EnhancedLocalDateTimeDeserializer INSTANCE = new EnhancedLocalDateTimeDeserializer();

    private EnhancedLocalDateTimeDeserializer() {
        super();
        log.trace("自定义 LocalDateTime 反序列化，转为中国风味的日期时间格式");
    }

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        String text = parser.getText();
        if (text.matches("\\d{13}")) {
            log.trace("自定义 LocalDateTime 反序列化，字符串毫秒级时间戳：{}", text);
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(text)), ZoneId.systemDefault());
        }
        if (text.matches("\\d{10}")) {
            log.trace("自定义 LocalDateTime 反序列化，字符串秒级时间戳：{}", text);
            return LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(text)), ZoneId.systemDefault());
        }
        if (parser.isExpectedStartObjectToken() || parser.isExpectedStartArrayToken()) {
            // 形如：[2025,3,25,14,19,43]
            log.trace("自定义 LocalDateTime 反序列化，使用默认的日期时间序列化器：{}", text);
            return LocalDateTimeDeserializer.INSTANCE.deserialize(parser, context);
        }
        return DateUtils.convertDateTime(text);
    }

}
